package com.yunheone.Jdbc;

import com.yunheone.control.Teachcon;
import com.yunheone.mode.TeacherUser;
import com.yunheone.view.Teach.TeachDell;
import com.yunheone.view.Teach.TeacherAdd;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 讲师管理
 */
public class TeacherJdbc {
    /**
     * 插入
     */
   public static void sava(){
       TeacherUser add = TeacherAdd.teacherAdd ();
       if  ( exit ( add.getId ())==1 ){
           System.out.println ("该用户已存在！");
       }else {
           String sql = "insert into teacher(no,name,sex,age) values(?,?,?,?)";
           PreparedStatement item = JdbcHelp.item ( sql, add.getId (), add.getName (), add.getSex (), add.getAge () );
           JdbcHelp.Update ( item );
           JdbcHelp.close ( item );
           System.out.println ( "添加成功！" );
       }
       Teachcon.teacRou ();
   }

/**
 * 删除
 */
    public static void dell(){
        String s = TeachDell.teachDell ();
        if (exit (s)==0){
            System.out.println ("该用户不存在！");
        }else {
            String sql = "delete from teacher where no=?";
            PreparedStatement item = JdbcHelp.item ( sql, s );
            JdbcHelp.Update ( item );
            JdbcHelp.close ( item );
            System.out.println ( "删除成功！" );
        }
        Teachcon.teacRou ();
    }
/**
 * 列表
 */
    public static List<TeacherUser> list(){
        List<TeacherUser> list=new ArrayList<> (  );
        String sql="select * from teacher ";
        PreparedStatement item = JdbcHelp.item ( sql );
        ResultSet query = JdbcHelp.Query ( item );
        if (query!=null){
            try {
                while(query.next ()){
                    String no = query.getString ( "no" );
                    String name = query.getString ( "name" );
                    String sex = query.getString ( "sex" );
                    String age = query.getString ( "age" );
                    TeacherUser teacherUser = new TeacherUser ( no, name, sex, age );
                    list.add ( teacherUser );
                }
            } catch (SQLException e) {
                e.printStackTrace ();
            }
        }
        JdbcHelp.close ( query,item );
        return list;
    }

    public static int exit(String id ){
        int i=0;
        String sql="select * from teacher where no=?";
        PreparedStatement item = JdbcHelp.item ( sql,id );
        ResultSet query = JdbcHelp.Query ( item );
        try {
            if (query.next ()){
                i=1;
            }
        } catch (SQLException e) {
            e.printStackTrace ();
        }
        return i;
    }
}
